package com.jf.session.CRUD;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-08-26
 * Time:11:05
 */
@WebServlet(name = "RetrieveSession", urlPatterns = "/retrieveSession")
public class RetrieveSession extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Object u = session.getAttribute("u");
        Object inform1 = session.getAttribute("inform1");

        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        if (u == null && inform1 == null) {
            out.println("<h1>Session is overdue</h1>");
            Cookie[] cookies = req.getCookies();
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("JSESSIONID")) {
                    out.println("<h1>Old Session ID is " + cookie.getValue() + "</h1>");
                    out.println("<h1>New Session ID is " + session.getId() + "</h1>");
                }
            }
        } else {
            out.println("<h1>Session's u attribute is " + u + "</h1>");
            out.println("<h1>Session's inform1 attribute is " + inform1 + "</h1>");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
